package com.stoneframe.base.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

/**
 * 跨域过滤器
 */
public class HttpCrossFilter implements Filter {
	
	/**允许文件类型*/
	private static String allowHeaders="content-type,origin,accept,authorization,x-requested-with";
	/**允许访问方式*/
    private static String allowMethods="POST, GET, OPTIONS, DELETE";
    /**允许访问时间*/
    private static Integer allowMaxAge=3600;
    /**访问缓存的最大超时间隔,单位秒,默认10秒*/
    private static Integer cacheMaxAge=10;

	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
			FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		HttpServletResponse response=(HttpServletResponse)servletResponse;
		response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", allowMethods);
        response.setHeader("Access-Control-Max-Age", allowMaxAge.toString());
        response.setHeader("Access-Control-Allow-Headers", allowHeaders);
        if(cacheMaxAge>0){//设置访问缓存超时间隔
	 		response.setHeader("Cache-Control","max-age="+cacheMaxAge);
	 	}
        chain.doFilter(servletRequest, servletResponse);
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		
	}

}
